package com.gitee.wsl.common.more.ext.glide.transform

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import androidx.core.content.ContextCompat
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.common.more.ext.glide.GlideImageLoadScope

import java.security.MessageDigest


/**
 * glide自定义图片遮罩
 */
/**
 * @param maskId If you change the mask file, please also rename the mask file, or Glide will get
 * the cache with the old mask. Because key() return the same values if using the
 * same make file name. If you have a good idea please tell us, thanks.
 */
class PhotoMaskTransformation(private val maskResId: Int) : BitmapTransformation() {
    override fun toString(): String {
        return "MaskTransformation(maskId=$maskResId)"
    }

    override fun equals(o: Any?): Boolean {
        return o is PhotoMaskTransformation &&
                o.maskResId == maskResId
    }

    override fun hashCode(): Int {
        return ID.hashCode() + maskResId * 10
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update((ID + maskResId).toByteArray(CHARSET))
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        val width = toTransform.width
        val height = toTransform.height
        val bitmap = pool[width, height, Bitmap.Config.ARGB_8888]
        bitmap.setHasAlpha(true)
        val mask = ContextCompat.getDrawable(application, maskResId)
        bitmap.density = toTransform.density
        val canvas = Canvas(bitmap)
        mask!!.setBounds(0, 0, width, height)
        mask.draw(canvas)
        canvas.drawBitmap(toTransform, 0f, 0f, paint)
        return bitmap
    }

    companion object {
        private const val VERSION = 1
        private const val ID = "jp.wasabeef.glide.transformations.PhotoMaskTransformation." + VERSION
        private val paint = Paint()

        init {
            paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OVER))
        }
    }
}

@SuppressLint("CheckResult")
fun GlideImageLoadScope.photoMask(maskResId: Int){
    requestOptions.transform(PhotoMaskTransformation(maskResId))
}